package cc.wsyw126.java.sycnAndVolaTest;

/**
 * 自增操作不是原子性操作，而且volatile也无法保证对变量的任何操作都是原子性的。
 * <p>
 * Created by junpeng.yang on 16/11/29.
 */
public class volatileTest {
    private volatile int inc = 0;

    public int increase() {
        return inc++;
    }

    public static void main(String[] args) {
        System.out.println("args = " + args);
        System.out.println(Thread.activeCount() + " thread numbers");

        final volatileTest test = new volatileTest();
        for (int i = 0; i < 10; i++) {
            new Thread() {
                public void run() {
                    for (int j = 0; j < 1000; j++)
                        test.increase();
                }

                ;
            }.start();
            System.out.println("Thread.activeCount() = " + Thread.activeCount());
        }

        while (Thread.activeCount() > 2) {  //保证前面的线程都执行完
            Thread.yield();
        }
        System.out.println(test.inc);
    }
}
